/*******************************************************************************
 * Copyright 2009 DCSpectrometer - http://code.google.com/p/dcspectrometer 
 *  
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 *  
 *     http://www.apache.org/licenses/LICENSE-2.0 
 *     
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License. 
 *******************************************************************************/
package com.dcspectrometer;

import java.awt.image.Raster;

/** Provides some simple image statistics */
public class ImageStatistics {
  private int minValues[];
  private int maxValues[];
  public static final int RED_CHANNEL = 0;
  public static final int GREEN_CHANNEL = 1;
  public static final int BLUE_CHANNEL = 2;
  private final int CHANNELS = 3;

  public ImageStatistics(Raster raster) throws IllegalArgumentException {
    minValues = new int[CHANNELS];
    maxValues = new int[CHANNELS];

    if (raster == null) {
      throw new IllegalArgumentException("Image is null.");
    }

    if (raster.getHeight() < 1 || raster.getWidth() < 1) {
      throw new IllegalArgumentException("Image must have at least 1 pixel.");
    }

    if (raster.getNumBands() < 3) {
      throw new IllegalArgumentException("Image must have RGB channels.");
    }

    int pixel[] = new int[3];
    raster.getPixel(0, 0, pixel);

    for (int i = 0; i < CHANNELS; i++) {
      minValues[i] = pixel[i];
      maxValues[i] = pixel[i];
    }

    for (int i = 0; i < raster.getWidth(); i++) {
      for (int j = 0; j < raster.getHeight(); j++) {
        raster.getPixel(i, j, pixel);

        for (int k = 0; k < CHANNELS; k++) {
          if (minValues[k] > pixel[k]) {
            minValues[k] = pixel[k];
          } else if (maxValues[k] < pixel[k]) {
            maxValues[k] = pixel[k];
          }
        }
      }
    }
  }
  
  public int getMax(int channel) throws IndexOutOfBoundsException {
    return maxValues[channel];
  }
  
  public int getMin(int channel) throws IndexOutOfBoundsException {
    return minValues[channel];
  }
}
